package com.sise.config;

import com.sise.model.po.WordContentPO;
import com.sise.service.LoadWordService;
import com.sise.service.impl.UgcCoreFilterImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 初始化加载文本内容到内存中
 *
 * @author idea
 * @data 2019/6/8
 */
@Component
public class ProviderLoadResourceConfig implements CommandLineRunner, LoadWordService {

    private static final String FILTER_KEY = "filter-word";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 加载数据
     *
     * @throws IOException
     */
    @Override
    public void loadStringInRedis() throws IOException {
        //第一次的时候需要从文本读取信息加载到内存中
        WordContentPO wordContentPO = (WordContentPO) redisTemplate.opsForValue().get(FILTER_KEY);
        if (wordContentPO == null) {
            List<String> wordList =getChineseWordList();

            wordContentPO = new WordContentPO();
            wordContentPO.setWordList(wordList);
            redisTemplate.opsForValue().set(FILTER_KEY, wordContentPO);
        }
        List<String> wordList = wordContentPO.getWordList();
        for (String word : wordList) {
            UgcCoreFilterImpl.put(word);
        }
        System.out.println("从redis读取敏感字");

    }

    /**
     * 获取中文的reader
     *
     * @return
     */
    private List<String> getChineseWordList(){
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                ClassLoader.getSystemResourceAsStream("sensi_words.txt")
                , StandardCharsets.UTF_8));
        List<String> wordList = new ArrayList<>(1024);
        try {
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                wordList.add(line);
            }
            return wordList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }

    /**
     * 获取英文的reader
     *
     * @return
     */
    private BufferedReader getEnglishWordReader(){
        return new BufferedReader(new InputStreamReader(
                ClassLoader.getSystemResourceAsStream("english_word.txt")
                , StandardCharsets.UTF_8));
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("加载数据到redis里面去");
        loadStringInRedis();
        System.out.println("加载完毕");
    }
}
